package com.spring.sjlong.service.impl;

import com.spring.sjlong.dao.UserMapper;
import com.spring.sjlong.model.dto.UserDto;
import com.spring.sjlong.model.pojo.User;
import com.spring.sjlong.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

@Service
public class UserService implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> getUserList(UserDto userDto) {
        if (null != userDto.getEndCreate()){
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(userDto.getEndCreate());
            calendar.add(Calendar.DATE,1);
            userDto.setEndCreate(calendar.getTime());
        }
        return userMapper.getUserList(userDto);
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.getUserById(id);
    }

    @Override
    public User getUserByName(String name) {
        return userMapper.getUserByName(name);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUser(User user) {
        if (null == user.getName())throw new IllegalArgumentException("用户名不可空！");
        User userByName = userMapper.getUserByName(user.getName());
        if (null != userByName)throw new IllegalArgumentException("用户名重复！");
        userMapper.addUser(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(User user) {
        if (null == user.getId())throw new IllegalArgumentException("id不可空！");
        if (null == user.getName())throw new IllegalArgumentException("用户名不可空！");
        if (null == user.getPassword())throw new IllegalArgumentException("用户密码不可空！");
        if (null == user.getCreateTime())throw new IllegalArgumentException("用户创建日期不可空！");
        User userById = userMapper.getUserById(user.getId());
        if (null == userById)throw new IllegalArgumentException("用户不存在！");
        user.setUpdateTime(new Date());
        userMapper.updateUser(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(Integer id) {
        userMapper.deleteUser(id);
    }
}
